import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/index.dart';
import '../../common/utils/payUtils.dart';

class SubscriptionController extends GetxController {
  SubscriptionController();

  // 选中的订阅计划，默认选择第一个（周订阅）
  final selectedPlan = 0.obs;

  // 按钮动画比例
  final restorePurchaseScale = 1.0.obs;
  final continueButtonScale = 1.0.obs;
  final subscription_list = subscription_list_data;

  // 选择订阅计划方法
  void selectPlan(int plan) {
    selectedPlan.value = plan;
    update(["subscription"]);
  }

  // 购买订阅方法
  Future<void> purchaseSubscription() async {
    debugPrint('购买订阅: ${selectedPlan.value}');
    final productId = subscription_list[selectedPlan.value]['id'] as String;
    try {
      // 显示加载动画
      SmartDialogHelper.showLoading(msg: "Processing your purchase...");
      // 调用支付工具
      final result = await PayUtils().buy_product(productId);
      // 关闭加载动画
      await SmartDialogHelper.dismiss();
      if (result) {
        // 购买成功，更新当前用户is_vip字段
        final user = UserService.to.get_now_user();
        if (user != null) {
          final updatedUser = user.copyWith(is_vip: true);
          UserService.to.set_user(updatedUser);
          debugPrint('订阅购买成功，已将is_vip字段设为true');
        } else {
          debugPrint('未找到当前用户，无法设置is_vip');
        }
        // 弹出英文成功提示
        SmartDialogHelper.show_success('Subscription purchased successfully!');
      } else {
        // 购买失败提示
        SmartDialogHelper.show_error(
          'Subscription purchase failed. Please try again.',
        );
        debugPrint('订阅购买失败');
      }
    } catch (e) {
      await SmartDialogHelper.dismiss();
      SmartDialogHelper.show_error(
        'Subscription purchase failed. Please try again.',
      );
      debugPrint('订阅购买异常: $e');
    }
  }

  _initData() {
    update(["subscription"]);
  }

  void restore_purchases() {
    PayUtils().restore_purchases();

    Future.delayed(const Duration(milliseconds: 500), () {
      SmartDialogHelper.show_success('Subscription restored successfully!');
    });
  }

  void onTap() {}

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
